<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="600px"
    :title="`${drawerProps.title}客户`"
    class="customer-drawer"
  >
    <div class="customer-view-container">
      <!-- 动态生成信息卡片 -->
      <template v-for="category in groupedFields" :key="category.name">
        <!-- 只在分类有可见字段时渲染卡片 -->
        <el-card v-if="hasVisibleFields(category)" shadow="hover" class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon class="header-icon">
                <component :is="getCategoryIcon(category.name)" />
              </el-icon>
              <span>{{ category.name }}</span>
              <span class="item-count" v-if="showItemCount(category)"> (共{{ countVisibleFields(category) }}项) </span>
            </div>
          </template>

          <div class="info-grid" :class="getGridClass(category)">
            <!-- 动态渲染每个字段 -->
            <template v-for="field in category.fields" :key="field.prop">
              <!-- 图片类型字段 -->
              <div v-if="field.renderType === 'img' && shouldShowField(field)" class="info-item avatar-item">
                <div class="info-label">{{ field.label }}</div>
                <div class="info-content">
                  <el-avatar
                    :size="120"
                    :src="getFieldValue(field.prop)"
                    class="customer-avatar"
                    v-if="getFieldValue(field.prop)"
                  >
                    <template #default>
                      <el-icon class="avatar-icon"><Picture /></el-icon>
                    </template>
                  </el-avatar>
                  <el-avatar :size="120" class="customer-avatar" v-else>
                    <el-icon class="avatar-icon"><Picture /></el-icon>
                  </el-avatar>
                </div>
              </div>

              <!-- 字符串数组字段 -->
              <div v-else-if="field.renderType === 'strArr' && shouldShowField(field)" class="info-item">
                <div class="info-label">{{ field.label }}</div>
                <div class="info-content">
                  <el-tag
                    v-for="(item, index) in getArrayFieldValue(field.prop)"
                    :key="index"
                    class="relation-tag"
                    :effect="getTagEffect(field)"
                    :type="getTagType(field)"
                  >
                    {{ item }}
                  </el-tag>
                  <span v-if="getArrayFieldValue(field.prop).length === 0">-</span>
                </div>
              </div>

              <!-- 对象数组字段 -->
              <div v-else-if="field.renderType === 'objArr' && shouldShowField(field)" class="info-item">
                <div class="info-label">{{ field.label }}</div>
                <div class="info-content">
                  <div class="objects-container" v-if="getFieldValue(field.prop)?.length > 0">
                    <div
                      v-for="(item, index) in getFieldValue(field.prop)"
                      :key="index"
                      class="object-card"
                      :class="{ 'object-card-highlight': index === 0 }"
                    >
                      <template v-for="subField in field.formConfig" :key="subField.key">
                        <div class="object-field" v-if="shouldShowSubField(item, subField)">
                          <div class="object-field-label">{{ subField.label }}</div>
                          <div class="object-field-value" :class="getSubFieldClass(subField)">
                            {{ item[subField.key] || "-" }}
                          </div>
                        </div>
                      </template>
                    </div>
                  </div>
                  <span v-else>-</span>
                </div>
              </div>

              <!-- 数字类型字段 -->
              <div v-else-if="isNumberField(field) && shouldShowField(field)" class="info-item">
                <div class="info-label">{{ field.label }}</div>
                <div class="info-content text-number">
                  {{ formatNumber(getFieldValue(field.prop)) }}
                  <span class="text-unit">{{ field.unit }}</span>
                </div>
              </div>

              <!-- 默认文本类型字段 -->
              <div v-else-if="shouldShowField(field)" class="info-item">
                <div class="info-label">{{ field.label }}</div>
                <div class="info-content" :class="getContentClass(field)">
                  {{ getFieldValue(field.prop) || "-" }}
                </div>
              </div>
            </template>
          </div>
        </el-card>
      </template>
    </div>

    <template #footer>
      <el-button @click="drawerVisible = false" class="close-btn">关闭</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { Picture } from "@element-plus/icons-vue";
import { Customer, ColumnForm } from "@/api/interface";

interface DrawerProps {
  title: string;
  row: Partial<Customer.CustomerInfo>;
  columns: ColumnForm<Customer.CustomerInfo>[];
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  title: "",
  row: {},
  columns: []
});

// 默认分类图标映射
const categoryIcons = {
  基础信息: "User",
  详细信息: "InfoFilled",
  经营信息: "TrendCharts",
  联系人信息: "Message",
  上下游信息: "Connection"
  // 可以继续添加更多映射
};

// 根据字段配置分组
const groupedFields = computed(() => {
  const fields = drawerProps.value.columns.filter(field => field.isShow && field.prop !== "operation");

  const categories = new Map<string, any[]>();

  fields.forEach(field => {
    const categoryName = field.category || "其他信息";
    if (!categories.has(categoryName)) {
      categories.set(categoryName, []);
    }
    categories.get(categoryName)?.push(field);
  });

  return Array.from(categories.entries()).map(([name, fields]) => ({
    name,
    fields: fields.sort((a, b) => (a.order || 999) - (b.order || 999))
  }));
});

// 获取分类图标组件
const getCategoryIcon = (categoryName: string) => {
  return categoryIcons[categoryName] || "InfoFilled";
};

// 获取字段值
const getFieldValue = (prop: string) => {
  return drawerProps.value.row[prop];
};

// 获取数组字段值
const getArrayFieldValue = (prop: string) => {
  const value = drawerProps.value.row[prop];
  if (typeof value === "string") {
    return value.split(",").filter(item => item.trim() !== "");
  }
  return value || [];
};

// 判断是否显示字段
const shouldShowField = (field: any) => {
  // 特殊处理对象数组字段
  if (field.renderType === "objArr") {
    const value = getFieldValue(field.prop);
    return value && value.length > 0;
  }
  return true;
};

// 判断是否显示子字段
const shouldShowSubField = (item: any, subField: any) => {
  return item[subField.key] !== undefined && item[subField.key] !== null && item[subField.key] !== "";
};

// 判断是否是数字字段
const isNumberField = (field: any) => {
  return ["annualOutputValue", "employeeCount"].includes(field.prop) || field.renderType === "number";
};

// 格式化数字显示
const formatNumber = (value: any) => {
  if (value === undefined || value === null || value === "") return "0";
  return Number(value).toLocaleString();
};

// 获取标签样式
const getTagEffect = (field: any) => {
  return field.prop.includes("upstream") ? "plain" : "light";
};

// 获取标签类型
const getTagType = (field: any) => {
  return field.prop.includes("upstream") ? "success" : "warning";
};

// 获取内容类名
const getContentClass = (field: any) => {
  const classes: string[] = [];
  if (field.prop === "enterpriseName") classes.push("text-important");
  if (["trainingExperience", "resourceInfo", "confusedQuestions", "otherInfo"].includes(field.prop)) {
    classes.push("pre-formatted");
  }
  return classes.join(" ");
};

// 获取子字段类名
const getSubFieldClass = (subField: any) => {
  const classes: string[] = [];
  if (subField.key === "phone") classes.push("text-phone");
  if (["trainingExperience", "remarks"].includes(subField.key)) {
    classes.push("pre-formatted");
  }
  return classes.join(" ");
};

// 获取网格类名
const getGridClass = (category: any) => {
  // 如果有图片字段，使用单列布局
  if (category.fields.some(f => f.renderType === "img")) return "cols-1";
  // 如果字段少于3个，使用两列布局
  if (countVisibleFields(category) <= 2) return "cols-2";
  return "";
};

// 计算分类中的可见字段数
const countVisibleFields = (category: any) => {
  return category.fields.filter(field => shouldShowField(field)).length;
};

// 判断分类是否有可见字段
const hasVisibleFields = (category: any) => {
  return category.fields.some(field => shouldShowField(field));
};

// 是否显示项目计数
const showItemCount = (category: any) => {
  return countVisibleFields(category) > 1;
};

// 接收父组件参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.customer-drawer {
  --el-drawer-padding-primary: 0;
  .el-drawer__header {
    padding: 16px 20px;
    margin-bottom: 0;
    border-bottom: 1px solid var(--el-border-color-light);
    box-shadow: 0 1px 4px rgb(0 0 0 / 5%);
    span {
      font-size: 16px;
      font-weight: 600;
    }
  }
  .el-drawer__body {
    padding: 0;
  }
  .el-drawer__footer {
    padding: 16px 20px;
    text-align: right;
    border-top: 1px solid var(--el-border-color-light);
  }
}
.customer-view-container {
  height: 100%;
  padding: 16px;
  overflow-y: auto;
}
.info-card {
  margin-bottom: 16px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  &:last-child {
    margin-bottom: 0;
  }
  .el-card__header {
    padding: 12px 16px;
    background-color: #f8fafc;
    border-bottom: 1px solid var(--el-border-color-light);
  }
}
.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: var(--el-text-color-primary);
  .header-icon {
    margin-right: 8px;
    color: var(--el-color-primary);
  }
  .item-count {
    margin-left: 8px;
    font-size: 12px;
    font-weight: normal;
    color: var(--el-text-color-secondary);
  }
}
.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
  padding: 8px;
  &.cols-2 {
    grid-template-columns: repeat(1, 1fr);
  }
}
.info-item {
  display: flex;
  flex-direction: column;
  &.avatar-item {
    grid-row: span 2;
    align-items: center;
  }
}
.info-label {
  margin-bottom: 6px;
  font-size: 13px;
  font-weight: 500;
  color: var(--el-text-color-secondary);
}
.info-content {
  min-height: 20px;
  font-size: 14px;
  line-height: 1.5;
  color: var(--el-text-color-primary);
  &.text-important {
    font-size: 15px;
    font-weight: 600;
  }
  &.text-number {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-color-primary);
  }
}
.text-unit {
  margin-left: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.pre-formatted {
  word-break: break-word;
  white-space: pre-wrap;
}
.customer-avatar {
  background-color: #f5f7fa;
  border: 1px dashed var(--el-border-color);
  .avatar-icon {
    font-size: 24px;
    color: var(--el-text-color-secondary);
  }
}
.objects-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.object-card {
  padding: 16px;
  background-color: #f8fafc;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  transition: all 0.3s ease;
  &:hover {
    box-shadow: 0 2px 12px rgb(0 0 0 / 8%);
  }
  &-highlight {
    background-color: rgb(var(--el-color-primary-rgb) 0.05);
    border-color: rgb(var(--el-color-primary-rgb) 0.2);
  }
}
.object-field {
  display: flex;
  margin-bottom: 8px;
  &:last-child {
    margin-bottom: 0;
  }
}
.object-field-label {
  min-width: 60px;
  margin-right: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}
.object-field-value {
  flex: 1;
  font-size: 13px;
  line-height: 1.5;
  color: var(--el-text-color-primary);
  &.text-phone {
    font-weight: 500;
  }
}
.relation-tag {
  height: 24px;
  padding: 0 12px;
  margin-right: 8px;
  margin-bottom: 8px;
  line-height: 24px;
  border-radius: 12px;
}
.close-btn {
  padding: 8px 20px;
  border-radius: 6px;
}
</style>
